<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品分类</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-row>
        <el-col>
          <el-button type="primary" @click="openAddDialog">添加分类</el-button>
        </el-col>
      </el-row>
      <tree-table
        class="treeTable"
        :data="categories"
        :columns="columns"
        :selection-type="false"
        :expand-type="false"
        show-index
        index-text="#"
        border
      >
        <!-- slot是名字，slot-scope是数据 -->
        <template slot="isOk" slot-scope="scope">
          <i class="el-icon-check" style="color:lightgreen;" v-if="scope.row.cat_deleted===false"></i>
          <i class="el-icon-close" style="color:red" v-else-if="scope.row.cat_deleted===true"></i>
        </template>
        <template slot="order" slot-scope="scope">
          <el-tag type="primary" size="mini" v-if="scope.row.cat_level===0">一级</el-tag>
          <el-tag type="success" size="mini" v-else-if="scope.row.cat_level===1">二级</el-tag>
          <el-tag type="warning" size="mini" v-else-if="scope.row.cat_level===2">三级</el-tag>
        </template>
        <template slot="caozuo" slot-scope="scope">
          <el-button size="mini" type="primary">编辑</el-button>
          <el-button size="mini" type="danger">删除</el-button>
        </template>
      </tree-table>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[3, 5, 10, 20]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </el-card>

    <!-- 点击添加用户按钮弹出对话框 -->
    <el-dialog title="提示" @close="closeDialog" :visible.sync="addDialogVisible" width="30%">
      <el-form
        :model="addCateform"
        :rules="addCateformrules"
        ref="closeDialogRef"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="分类名称" prop="cat_name">
          <el-input v-model="addCateform.cat_name"></el-input>
        </el-form-item>
        <el-form-item label="父级分类">
          <el-cascader
            :key="iscascader"
            v-model="cascaderValue"
            :options="parentCateList"
            expand-trigger="hover"
            :props="cascaderProps"
            @change="handleCascaderChange"
          ></el-cascader>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addCate">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 商品分类列表，默认为空
      categories: [],
      queryInfo: {
        type: '',
        pagenum: 1,
        pagesize: 5
      },
      total: 0,
      // 为table指定列的定义
      columns: [
        {
          label: '分类名称',
          prop: 'cat_name'
        },
        {
          label: '是否有效',
          type: 'template',
          template: 'isOk'
        },
        {
          label: '排序',
          type: 'template',
          template: 'order'
        },
        {
          label: '操作',
          type: 'template',
          template: 'caozuo'
        }
      ],
      // 点击添加按钮弹出对话框
      addDialogVisible: false,
      addCateform: {
        cat_name: '',
        cat_level: '',
        cat_pid: ''
      },
      // 添加用户表单的验证规则
      addCateformrules: {
        cat_name: [
          { required: true, message: '分类名称', trigger: 'blur' },
          { min: 1, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
      },
      // 父级分类列表
      parentCateList: [],
      // 级联选择框的配置选项
      cascaderProps: {
        value: 'cat_pid',
        children: 'children',
        label: 'cat_name'
      },
      cascaderValue: [],
      iscascader: 0
    }
  },
  created() {
    this.getCategories()
  },
  methods: {
    // 重置表单
    closeDialog() {
      console.log('关闭对话框')
      this.$refs.closeDialogRef.resetFields()
      this.addCateform.cat_pid = 0
      this.addCateform.cat_level = 0
      this.cascaderValue = []
    },
    handleCascaderChange() {
      console.log(this.cascaderValue)
      if (this.cascaderValue.length > 0) {
        // 当前分类的父级id
        this.addCateform.cat_pid = this.cascaderValue[
          this.cascaderValue.length - 1
        ]
        // 为当前分类的等级赋值
        this.addCateform.cat_level = this.cascaderValue.length
        return
      } else {
        this.addCateform.cat_pid = 0
        // 为当前分类的等级赋值
        this.addCateform.cat_level = 0
      }
      console.log(this.addCateform)
    },
    // 添加分类操作
    addCate() {
      this.$refs.closeDialogRef.validate(async valid => {
        if(!valid){
          return this.$message.error('表单验证有误，请检查数据格式')
        }
        const {data:res} = await this.$http.post('categories',this.addCateform)
        if(res.meta.status !== 201){
          return this.$message.error('添加分类失败')
        }
        console.log(res.data);
        
        this.$message.success('添加分类成功')
        this.addDialogVisible = false
      })
      
    },
    // 获取父级分类的数据列表
    async getParentCateList() {
      // 获取前两级的分类
      const { data: res } = await this.$http.get('categories', {
        params: { type: 2 }
      })

      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }

      this.iscascader++
      console.log(this.iscascader)
      this.parentCateList = res.data
    },
    // 点击添加分类按钮弹出对话框
    openAddDialog() {
      this.getParentCateList()
      console.log('kkk')

      this.addDialogVisible = true
    },
    async getCategories() {
      const { data: res } = await this.$http.get('categories', {
        params: this.queryInfo
      })
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.categories = res.data.result
      this.total = res.data.total
      // console.log(res.data)
    },
    handleSizeChange(val) {
      this.queryInfo.pagesize = val
      this.getCategories()
      console.log(`每页 ${val} 条`)
    },
    handleCurrentChange(val) {
      this.queryInfo.pagenum = val
      this.getCategories()
      console.log(`当前页: ${val}`)
    }
  }
}
</script>

<style lang="less" scoped>
.treeTable {
  margin-top: 15px;
}
.el-cascader {
  width: 100%;
}
</style>